/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/


namespace GearBlog.Web.Models
{
	using System;
	using System.Collections.Generic;
	using System.Text;
	using System.Text.RegularExpressions;
	using Castle.ActiveRecord;
	using Castle.Components.Validator;
	using GearBlog.Web.Helpers;
	using Iesi.Collections.Generic;
	using NHibernate.Expression;

	[ActiveRecord]
	public class Post:ExtendedActiveRecordBase<Post>
	{
		private string _title;
		private string _body;
		private DateTime _createdAt;
		private User _author;
		private ISet<User> _commentSubscribers=new HashedSet<User>();
		private ISet<Comment> _comments=new HashedSet<Comment>();
        private ISet<Tag> _tags=new HashedSet<Tag>();

		[Property(NotNull=true)]
		public DateTime CreatedAt
		{
			get { return _createdAt; }
			set { _createdAt = value; }
		}

		[Property(Length = 250, NotNull = true), ValidateNonEmpty]
		public string Title
		{
			get { return _title; }
			set { _title = value; }
		}

		[Property(Length = 100000, NotNull = true), ValidateNonEmpty]
		public string Body
		{
			get { return _body; }
			set { _body = value; }
		}

        public string GetBodySummary(int maxLineBreaks, int maxCharacters)
        {
            // check for max line breaks
            string[] contentLines = _body.Split(new string[] { "\r\n" },StringSplitOptions.RemoveEmptyEntries);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < maxLineBreaks && i<contentLines.Length ; i++)
            {
                sb.AppendFormat("{0}\r\n",contentLines[i]);
				if (sb.Length > maxCharacters) break;
            }
            return sb.ToString();
        }

		[BelongsTo]
		public User Author
		{
			get { return _author; }
			set { _author = value; }
		}

        [HasMany(typeof(Comment))]
        public ISet<Comment> Comments
		{
			get { return _comments; }
			set { _comments = value; }
		}

        [HasAndBelongsToMany(Table = "PostTag", ColumnKey = "PostId", ColumnRef = "TagId",Inverse=false)]
        public ISet<Tag> Tags
        {
            get { return _tags; }
            set { _tags = value; }
        }

		[HasAndBelongsToMany(Table="PostCommentUserSubscriptions", ColumnKey = "PostId", ColumnRef = "UserId")]
		public ISet<User> CommentSubscribers
		{
			get { return _commentSubscribers; }
			set { _commentSubscribers = value; }
		}

		public string TagsString
        {
            get 
            {
                StringBuilder sb = new StringBuilder();
                foreach (Tag tag in _tags)
                {
                    sb.AppendFormat("{0}, ", tag.Name);
                }
            	return Regex.Replace(sb.ToString(), @",\s$", "");
            }
            set 
            {
                string[] tagStrings = value.Split(',');
                
                foreach (string tagString in tagStrings)
                {
                    string trimmedTagString = tagString.Trim();
                    Tag tag = Tag.FindFirst(new EqExpression("Name", trimmedTagString));

                    if (tag==null)
                    {
                        tag = new Tag();
                        tag.Name = trimmedTagString;
                        tag.Save();
                        Tags.Add(tag);
                    }
                    else
                    {
                        if (!Tags.Contains(tag)) Tags.Add(tag);
                    }
                }
            }

        }

		public Comment[] GetPostedComments()
		{
			List<Comment> postedComments=new List<Comment>();
			foreach (Comment comment in _comments)
			{
				if (comment.Status==CommentStatus.Posted)
					postedComments.Add(comment);
			}
			return postedComments.ToArray();
		}

		public static Post[] FindAllAfter(DateTime date)
		{
			return Post.FindAll(Order.Desc("CreatedAt"),new GeExpression("CreatedAt", date));
		}

		public static Post[] FindAllByYearMonth(int year, int month)
		{
			//get first day and last day of the month
			DateTime firstDayOfMonth=new DateTime(year, month, 1);
			DateTime lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);

			return Post.FindAll(Order.Desc("CreatedAt"), new BetweenExpression("CreatedAt", firstDayOfMonth, lastDayOfMonth));

		}

	}
}
